package forum.dao.memory;

import forum.entities.Entity;
import forum.dao.GenericDAO;
import forum.exceptions.CreateExistingEntityException;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Iterator;

public abstract class MemoryGenericDAO<T extends Entity> implements GenericDAO<T> {


    private HashMap<BigInteger,T> entityTable = new HashMap<BigInteger, T>();
    private static BigInteger lastInsertedKey = BigInteger.ZERO;

    @Override
    public T create() {
        T entity = newEntity();
        entityTable.put(lastInsertedKey,entity);
        return entity;
    }

    @Override
    public T read(BigInteger id) {
        return entityTable.get(id);
    }

    @Override
    public void update(T entity) throws CreateExistingEntityException{
        if (entity.getId() == null) {
            throw new IllegalArgumentException("Can't update not existing entity");
        }
        entityTable.put(entity.getId(),entity);
    }

    @Override
    public void delete(BigInteger id) {
        entityTable.remove(id);
    }

    protected Iterator<T> getEntitiesIterator() {
        return entityTable.values().iterator();
    }

    protected static BigInteger getNewKey() {
        lastInsertedKey = lastInsertedKey.add(BigInteger.ONE);
        return lastInsertedKey;
    }

    protected abstract T newEntity();

}
